package com.example.app1;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.RadioGroup;

import androidx.appcompat.app.AppCompatActivity;

public class SharePreference10Activity extends AppCompatActivity {
    private final String preferences_name="user";
    private EditText etname;
    private EditText etage;
    private RadioGroup sex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_preference10);

        etname = (EditText)findViewById(R.id.editText1);
        etage = (EditText)findViewById(R.id.editText2);
        sex = (RadioGroup)findViewById(R.id.radioGroup1);
        SharedPreferences preferences = getSharedPreferences(preferences_name, Context.MODE_PRIVATE);
        etname.setText(preferences.getString("name", ""));
        etage.setText(preferences.getString("city", ""));
        sex.check(preferences.getInt("gender", -1));
    }
    @Override
    protected void onStop() {
        //获得sharedpreferences对象
        SharedPreferences mypreferences = getSharedPreferences(preferences_name, Context.MODE_PRIVATE);
        //获得sharedpreferences.editor
        SharedPreferences.Editor editor = mypreferences.edit();
        //保存组件中的值
        editor.putString("name", etname.getText().toString());
        editor.putString("city", etage.getText().toString());
        editor.putInt("gender", sex.getCheckedRadioButtonId());
        //提交保存的结果
        editor.commit();
        super.onStop();
    }
}